/**
 * QueryImageListTask.java Create on 2012-8-4     
 *      
 * Copyright (c) 2012-8-4 by yiming     
 *      
 * @author <a href="alenzhangym@hotmail.com">Yiming</a>     
 * @version 1.0 
 */

package com.yimi.taskmanager;

import android.util.Log;

import com.yimi.common.Message;
import com.yimi.common.MessageType;
import com.yimi.service.ImageEntity;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * TODO 功能描述
 * 
 * @author Yiming
 * @version 1.0
 */
public class DownloadImageTask extends Task {

    private HttpURLConnection conn = null;
    private DataInputStream input = null;

    private boolean close;
    public static final int MAX_BITMAP_SIZE = 5237760;
    public static final int MAX_SEND_SIZE = MAX_BITMAP_SIZE / 5;

    public DownloadImageTask(String url) {
        super(url);
        close = false;
    }

    /*
     * (non-Javadoc)
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run() {
        if (close)
            return;
        Log.e(this.getClass().getName(), "request  is :" + taskCommand);
        try {
            conn = (HttpURLConnection) new
                    URL(taskCommand).openConnection(); 
            conn.setDoInput(true);
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(60000);
            conn.connect();
            if (close)
            {
                conn.disconnect();
                return;
            }
            int k = conn.getResponseCode();
            if (k != 200) {
                addQueryMapFailedMessage(MessageType.TYPE_QUERYMAP_HTTPFAILED,
                        taskCommand);
            } else {
                input = new DataInputStream(
                        conn.getInputStream());
                if (close)
                {
                    try {
                        input.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    conn.disconnect();
                    return;
                }
                int size = conn.getContentLength();
                byte[] buffer = new byte[MAX_SEND_SIZE];
                int readLenth = input.read(buffer, 0, MAX_SEND_SIZE);
                while (readLenth!=-1) {
                    if (close)
                    {
                        try {
                            input.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        conn.disconnect();
                        return;
                    }
                    byte[] readBuffer = new byte[readLenth];
                    System.arraycopy(buffer, 0, readBuffer, 0, readLenth);
                    buffer = new byte[MAX_SEND_SIZE];
                    readLenth = input.read(buffer, 0, MAX_SEND_SIZE);
                    ImageEntity imageEntity = new ImageEntity();
                    imageEntity.setFileURL(taskCommand);
                    imageEntity.setImage(readBuffer);
                    imageEntity.setImageSize(size);
                    Message message = new Message(MessageType.EVENT_QUDERYFILEVIEWSUCCESS);
                    message.setType(MessageType.TYPE_DOWNLOAD_PROGRESS);
                    message.setResult(imageEntity);
                    addMessage(message);
                }
                if (close)
                {
                    try {
                        input.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    conn.disconnect();
                    return;
                }
                ImageEntity imageEntity = new ImageEntity();
                imageEntity.setFileURL(taskCommand);
                imageEntity.setImageSize(size);
                byte[] data = new byte[0];
                imageEntity.setImage(data);
                Message message = new Message(
                        MessageType.EVENT_QUDERYFILEVIEWSUCCESS);
                message.setType(MessageType.TYPE_DOWNLOAD_END);
                message.setResult(imageEntity);
                addMessage(message);
                close = true;
            }
        } catch (Exception e) {
            Log.e(this.info(), "e is "+e.getMessage());
            addQueryMapFailedMessage(MessageType.TYPE_QUEYRMAP_FAILED,
                    taskCommand);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }

    }

    protected void addQueryMapFailedMessage(int type, String fileURL) {
        ImageEntity imageEntity = new ImageEntity();
        imageEntity.setFileURL(fileURL);
        imageEntity.setImage(new byte[0]);
        super.addFailedMessage(MessageType.EVENT_QUERYFILEVIEWFAILED, type, imageEntity);
    }

    public synchronized void stop() {
        this.listners.removeAllElements();
        close = true;
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    /*
     * (non-Javadoc)
     * @see com.yimi.taskmanager.Task#info()
     */
    @Override
    public String info() {
        return "Download task ";
    }

}
